﻿#region Copyright
// Copyright (c) 2011-2012 RaisingForce Team (Alikin Sergey)
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using RaisingForce.Raise.Presentation.Rules;

namespace RaisingForce.Raise.Presentation.ViewModel.Specialized
{
    public abstract class SettingBoxViewModel<T> :
        SettingBoxBaseViewModel
    {
        #region Constructors

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        protected SettingBoxViewModel(
            string errorText,
            string errorEmptyText,
            Func<string> getSettingText)
            : base(errorText, errorEmptyText)
        {
            Contract.Requires(ValidationRuleRules.ErrorTextIsValid(errorText));
            Contract.Requires(ValidationRuleRules.ErrorTextIsValid(errorEmptyText));
            this.getSettingText = getSettingText;
            this.updateText();
        }

        #endregion

        #region Private Declarations

        private readonly Func<string> getSettingText;

        private void updateText()
        {
            if (this.getSettingText != null)
            {
                this.Text = this.getSettingText();
            }
        }

        #endregion

        #region Protected Declarations

        protected abstract BaseValidationRule<T> TextValidationRule { get; }

        protected Action<T> SetRealProperty { get; set; }

        #endregion

        #region Base Overrides

        protected override void invalidateValue()
        {
            base.invalidateValue();
            this.updateText();
        }

        #endregion

        #region ViewModel Properties Aids

        private void setProperty(
            string propertyName,
            string value,
            ref string state)
        {
            if (!object.Equals(value, state))
            {
                this.ClearValidationCache();
                T valueOfT;
                BaseValidationRule<T> rule = this.TextValidationRule;
                if (this.SetRealProperty != null)
                {
                    if (rule.TryParseValue(value, out valueOfT))
                    {
                        if (ValidationRuleSucceeded(rule, valueOfT))
                        {
                            this.SetRealProperty(valueOfT);
                        }
                    }
                }
                state = value;
                this.OnPropertyChanged(propertyName);
            }
        }

        #endregion

        #region ViewModel Properties

        private const string propText = "Text";

        private string text;

        public string Text
        {
            get { return this.text; }
            set
            {
                this.setProperty(propText, value, ref this.text);
            }
        }

        private string measureText;

        public string MeasureText
        {
            get { return this.measureText; }
            set
            {
                this.SetProperty(
                    ref this.measureText,
                    value,
                    "MeasureText");
            }
        }

        #endregion

        #region Validation Declarations

        private static readonly IEnumerable<string> validatedProperties =
            GetValidatedProperties(new string[] { propText });

        protected override IEnumerable<string> ValidatedProperties
        {
            get { return validatedProperties; }
        }

        protected override string getValidationError(string propertyName)
        {
            string error;
            switch (propertyName)
            {
                case propText:
                    error = GetValidationRuleResult(this.TextValidationRule, this.text);
                    break;
                default:
                    error = null;
                    break;
            }
            return error;
        }

        #endregion
    }
}
